<template>
  <div class="login-container">
    <div class="card">
      <h2>用户登录</h2>
      
      <!-- 登录方式选择 -->
      <div class="login-type-tabs">
        <button 
          :class="['tab-btn', loginType === 'account' ? 'active' : '']"
          @click="loginType = 'account'"
        >
          账号登录
        </button>
        <button 
          :class="['tab-btn', loginType === 'phone' ? 'active' : '']"
          @click="loginType = 'phone'"
        >
          手机号登录
        </button>
      </div>

      <!-- 账号密码登录表单 -->
      <form v-if="loginType === 'account'" @submit.prevent="handleAccountLogin">
        <div class="form-group">
          <label>用户名</label>
          <input 
            type="text" 
            v-model="accountForm.username" 
            required
            placeholder="请输入用户名"
          >
        </div>

        <div class="form-group">
          <label>密码</label>
          <input 
            type="password" 
            v-model="accountForm.password" 
            required
            placeholder="请输入密码"
          >
        </div>

        <button type="submit" class="submit-btn">登录</button>
      </form>

      <!-- 手机号登录表单 -->
      <form v-if="loginType === 'phone'" @submit.prevent="handlePhoneLogin">
        <div class="form-group">
          <label>手机号</label>
          <input 
            type="tel" 
            v-model="phoneForm.phone" 
            required
            placeholder="请输入11位手机号码"
            @input="validatePhone"
            @blur="validatePhone"
            maxlength="11"
            :class="{ 'error': phoneError }"
          >
          <div v-if="phoneError" class="error-message">{{ phoneError }}</div>
        </div>

        <div class="form-group verification-code">
          <label>验证码</label>
          <div class="code-input-group">
            <input 
              type="text" 
              v-model="phoneForm.verificationCode" 
              required
              placeholder="请输入6位验证码"
              maxlength="6"
              :class="{ 'error': verificationCodeError }"
            >
            <button 
              type="button" 
              class="send-code-btn"
              :disabled="!canSendCode || countdown > 0"
              @click="sendVerificationCode"
            >
              {{ countdown > 0 ? `${countdown}s后重新发送` : '发送验证码' }}
            </button>
          </div>
          <div v-if="verificationCodeError" class="error-message">{{ verificationCodeError }}</div>
        </div>

        <button 
          type="submit" 
          class="submit-btn"
          :disabled="!phoneFormValid"
        >
          手机号登录
        </button>
      </form>

      <!-- 用户身份选择 -->
      <div class="user-type-selection">
        <h3>选择登录身份</h3>
        <div class="user-type-buttons">
          <button 
            class="user-type-btn runner"
            @click="navigateToRunnerLogin"
          >
            🚴 我是跑腿员
          </button>
          <button 
            class="user-type-btn admin"
            @click="navigateToAdminLogin"
          >
            👨‍💼 我是管理员
          </button>
        </div>
      </div>

      <p class="link-text">
        没有账号？<router-link to="/user/register">去注册</router-link>
      </p>
    </div>
  </div>
</template>

<script setup>
import request from '@/utils/request';
import { ElMessage } from 'element-plus';
import { computed, ref, watch } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter()

// 登录方式
const loginType = ref('account')

// 账号登录表单
const accountForm = ref({
  username: '',
  password: ''
})

// 手机号登录表单
const phoneForm = ref({
  phone: '',
  verificationCode: ''
})

// 错误信息
const errors = ref({
  phone: '',
  verificationCode: ''
})

// 验证码倒计时
const countdown = ref(0)

// 计算属性：是否可以发送验证码
const canSendCode = computed(() => {
  return phoneForm.value.phone && !errors.value.phone && countdown.value === 0
})

// 计算属性：手机号登录表单是否有效
const phoneFormValid = computed(() => {
  return phoneForm.value.phone && 
         phoneForm.value.verificationCode &&
         !errors.value.phone &&
         !errors.value.verificationCode
})

// 错误信息计算属性
const phoneError = computed(() => errors.value.phone)
const verificationCodeError = computed(() => errors.value.verificationCode)

// 监听手机号变化，清除验证码错误
watch(() => phoneForm.value.phone, () => {
  if (errors.value.verificationCode) {
    errors.value.verificationCode = ''
  }
})

// 验证手机号
const validatePhone = () => {
  const phone = phoneForm.value.phone
  
  if (!phone) {
    errors.value.phone = '手机号不能为空'
    return false
  }

  if (!/^1[3-9]\d{9}$/.test(phone)) {
    errors.value.phone = '请输入正确的11位手机号码'
    return false
  }

  errors.value.phone = ''
  return true
}

// 发送验证码
const sendVerificationCode = async () => {
  if (!canSendCode.value) return

  // 验证手机号格式
  if (!validatePhone()) {
    return
  }

  try {
    const res = await request.post('/user/register/send', {
      phone: phoneForm.value.phone
    })
    
    // 开始倒计时
    countdown.value = 120
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
    
    if (res.code == 500) {
      alert('发送验证码失败: ' + res.message)
    } else {
      alert('验证码已发送')
    }
  } catch (error) {
    console.error('发送验证码失败', error)
    if (error.response?.data?.message) {
      alert('发送验证码失败: ' + error.response.data.message)
    } else {
      alert('发送验证码失败，请重试')
    }
  }
}

// 验证验证码
const validateVerificationCode = () => {
  const code = phoneForm.value.verificationCode
  
  if (!code) {
    errors.value.verificationCode = '验证码不能为空'
    return false
  }

  if (!/^\d{6}$/.test(code)) {
    errors.value.verificationCode = '验证码必须是6位数字'
    return false
  }

  errors.value.verificationCode = ''
  return true
}

// 账号密码登录
const handleAccountLogin = async () => {
  try {
    const res = await request.post('/user/login', accountForm.value)
    if (res.code == 500) {
      ElMessage.error(res.message)
    } else {
      handleLoginSuccess(res)
    }
  } catch (error) {
    console.error('登录失败', error)
    ElMessage.error('登录失败，请检查账号密码')
  }
}

// 手机号登录
const handlePhoneLogin = async () => {
  // 验证手机号
  if (!validatePhone()) {
    return
  }

  // 验证验证码
  if (!validateVerificationCode()) {
    return
  }

  try {
    const res = await request.get('/user/login/phone', {
      params: {
        phone: phoneForm.value.phone,
        code: phoneForm.value.verificationCode
      }
    })
    
    if (res.code == 500) {
      alert(res.message)
    } else {
      handleLoginSuccess(res)
    }
  } catch (error) {
    console.error('手机号登录失败', error)
    if (error.response?.data?.message) {
      alert('登录失败: ' + error.response.data.message)
    } else {
      alert('登录失败，请检查验证码')
    }
  }
}

// 登录成功处理
const handleLoginSuccess = (res) => {
  console.log(res)
  // 存储token和用户信息
  localStorage.setItem('token', res.data.token)
  localStorage.setItem('user', JSON.stringify(res.data.user))
  
  console.log("login验证")
  
  // 检查审核状态
  if (res.data.user.status !== 0) {
    ElMessage.error('账号未通过审核或待审核')
    return
  }
  
  ElMessage.success('登录成功')
  // 根据用户类型跳转
   router.push('/user/index')
}

// 跳转到跑腿员登录
const navigateToRunnerLogin = () => {
  router.push('/login')
}

// 跳转到管理员登录
const navigateToAdminLogin = () => {
  router.push('/admin/login')
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
}

.card {
  width: 400px;
  padding: 2.5rem;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
}

.login-type-tabs {
  display: flex;
  margin-bottom: 1.5rem;
  border-bottom: 1px solid #eee;
}

.tab-btn {
  flex: 1;
  padding: 0.8rem;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 1rem;
  color: #666;
  border-bottom: 2px solid transparent;
}

.tab-btn.active {
  color: #3B82F6;
  border-bottom-color: #3B82F6;
}

.form-group {
  margin-bottom: 1.5rem;
  position: relative;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #666;
  font-size: 0.9rem;
}

.form-group input {
  width: 95%;
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  transition: border-color 0.3s;
}

.form-group input:focus {
  outline: none;
  border-color: #3B82F6;
}

.form-group input.error {
  border-color: #ff4d4f;
}

.error-message {
  color: #ff4d4f;
  font-size: 0.8rem;
  margin-top: 0.3rem;
}

.verification-code .code-input-group {
  display: flex;
  gap: 0.5rem;
}

.verification-code input {
  flex: 1;
}

.send-code-btn {
  padding: 0.8rem 1rem;
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  white-space: nowrap;
  transition: background-color 0.3s;
}

.send-code-btn:not(:disabled):hover {
  background-color: #e9ecef;
}

.send-code-btn:disabled {
  background-color: #e9ecef;
  cursor: not-allowed;
  color: #999;
}

.submit-btn {
  width: 100%;
  padding: 0.9rem;
  background-color: #3B82F6;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-bottom: 1.5rem;
}

.submit-btn:hover:not(:disabled) {
  background-color: #2563EB;
}

.submit-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.user-type-selection {
  margin: 2rem 0;
  padding: 1.5rem;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.user-type-selection h3 {
  text-align: center;
  margin-bottom: 1rem;
  color: #333;
}

.user-type-buttons {
  display: flex;
  gap: 1rem;
}

.user-type-btn {
  flex: 1;
  padding: 1rem;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  background: white;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.3s;
}

.user-type-btn:hover {
  border-color: #3B82F6;
  transform: translateY(-2px);
}

.user-type-btn.runner {
  background: linear-gradient(135deg, #e3f2fd, #bbdefb);
}

.user-type-btn.admin {
  background: linear-gradient(135deg, #f3e5f5, #e1bee7);
}

.link-text {
  text-align: center;
  margin-top: 1.2rem;
  font-size: 0.9rem;
}

.link-text a {
  color: #3B82F6;
  text-decoration: none;
}
</style>